package com.campustradingwall.controller;

import com.campustradingwall.dao.UserDao;
import com.campustradingwall.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserDao userDao = new UserDao();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");

        // 检查用户名是否已存在
        if (userDao.getUserByUsername(username) != null) {
            request.setAttribute("error", "用户名已存在，请换一个。");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }

        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password); // 注意：实际项目中应加密
        newUser.setPhone(phone);
        newUser.setRole("user"); // 默认为普通用户
        newUser.setStatus("active"); // 默认状态为激活
        newUser.setAvatar("default_avatar.png"); // 默认头像

        userDao.createUser(newUser);

        // 注册成功后重定向到登录页面
        response.sendRedirect(request.getContextPath() + "/login.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 直接访问/register时，也显示注册页面
        request.getRequestDispatcher("register.jsp").forward(request, response);
    }
} 